﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace Step4.Unit2.Controllers
{
    // 请求视图
    public class RequestTestController : Controller
    {
        /// <summary>
        /// 表单提交相应方法
        /// </summary>
        /// <returns></returns>
        public IActionResult Search()
        {
            List<Student> students = new()
            {
                new Student(1,"余冰"),
                new Student(2,"刘钦响"),
                new Student(3,"赵宁宁")
            };
            var studentName = Request.Query["studentName"].ToString();
            if (!string.IsNullOrEmpty(studentName))
            {
                // 模糊查询
                students = students.Where(e => e.Name.Contains(studentName)).ToList();
            }
            return View(students);// 通过视图模型传值
        }

        /// <summary>
        /// ajax请求
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult MyList()
        {
            List<Student> students = new()
            {
                new Student(1,"余冰"),
                new Student(2,"刘钦响"),
                new Student(3,"赵宁宁")
            };
            
            var studentName =Request.Query["studentName"].ToString();
            
            // HttpUtility类提供在http请求中的url的"编码"和"解码"，
            // 其中，UrlDecode()方法用来进行解码
            var token = HttpUtility.UrlDecode(Request.Headers["mytoken"].ToString()); // 拿到头后，如果请求时对头中信息进行了编码，就需要解码才能用


            if (!string.IsNullOrEmpty(studentName))
            {
                // 模糊查询
                students = students.Where(e => e.Name.Contains(studentName)).ToList();
            }

            // 响应体
            return View(students);// 通过视图模型传值
        }


        // Http响应
        public async Task<IActionResult> TestResponse()
        {
            // 设置响应头 ： Response.Headers["Content-Type"] ，绝大部分相应头都被抽象成属性放在Response里了
            Response.ContentType = "text/plain;charset=utf8";
            await Response.WriteAsync("你好呀，测试响应体",Encoding.UTF8);
            // 平时不会这么用，但是如果你发现相应的内容乱码了，那你就需要设置响应头

            return new EmptyResult();
        }

    }

    // 声明Student类型记录
    public record Student(int Id,string Name);
}
